<template>
  <!-- <collectApp></collectApp> -->
  <div style="height: 100vh">
    <div id="nav-top" class="fixed header sticky">
      <!-- <NavBar :onClickLeft="onClickLeft">AI会话</NavBar> -->
      <NavBar>AI会话</NavBar>
    </div>

    <div class="page-mod" style="padding-top: 6.5rem;" :style="{ paddingBottom: pagePaddingBottom + 'rpx' }">
      <!-- <Welcome2></Welcome2>
      <Welcome1></Welcome1> -->
      <Welcome v-show="!chatStore.chatList || !chatStore.chatList.length"></Welcome>
      <ChatList></ChatList>
    </div>
    <div id="bottom-operate-wrap" class="fixed-footer">
      <div id="fixed-input-wrap" class="flex">

        <div id="input-wrap" class="input-wrap">

          <textarea v-model="userInput" :cursor-spacing="70" :maxlength="-1" @linechange="lineChange" ref="questionInput"
            auto-height @input="handleInput" :style="{
              minHeight: '40rpx',
              maxHeight: maxHeight,
              overflowY: 'auto'
            }" placeholder="快来输入问题问我吧..."></textarea>
          <button class="send" type="primary" round @click="inputAskAi">
            <i class="ai-icon-paper-plane" style="font-size: 22px"></i>
          </button>
        </div>
        <!-- <van-field v-model="userAsk" ref="questionInput" @input="userChangeInput" placeholder="快来输入问题问我吧..." /> -->
      </div>
      <div class="bottom-list">
        <button id="clear-chat" round @click="clearChat">
          <!-- <i class="ai-icon-paper-plane" style="font-size: 22px;"></i> -->
          <div style="display: flex"><i class="ai-icon-jia"
              style="display:inline-block;margin-right: 14rpx;font-size: 24rpx;"></i>新话题
          </div>
        </button>
        <button class="switch-deep-btn" @click="switchModal" :class="{ active: modalType == 'r1' }">
          <i class="iconfont ai-icon-shendusikao"
            style="display:inline-block;margin-right: 14rpx;font-size:28rpx;"></i>深度思考
        </button>
      </div>
    </div>

    <van-toast id="van-toast"></van-toast>
  </div>
  <ExpireVipModal v-model:expireVipModal="expireVipModal">您的会员已过期，订阅即可继续享用会员权益</ExpireVipModal>
  <!-- <div v-if="showPage">
    <page-container :show="showPage" :overlay="false" @beforeleave="beforeleave"></page-container>
  </div> -->
</template>

<script setup>
import { onMounted, computed, provide, ref, toDisplayString, nextTick } from "vue";
import { getUserInfo } from "@/api/login";
import Toast from "@vant/weapp/dist/toast/toast";
// import Welcome2 from './child/Welcome2.vue';
// import Welcome1 from './child/Welcome1'
import Welcome from "./child/Welcome.vue";
import ChatList from "./child/ChatList";
import { useChatStore, useUserStore } from "@/store/modules";
import { addAiAnswer, handleAiResponse } from "./chatUtils";
import { getAnswerList } from "@/api/chat";
import storage from "@/utils/storage";
import { loginRedirect } from "@/utils/auth";
import ChooseAiModal from './child/ChooseAiModal.vue';
import { getToken } from '@/utils/auth';
// import { getApp } from '@dcloudio/uni-h5';
import {
  onLoad,
  onShow,
  onHide,
  onShareAppMessage,
  onShareTimeline,
} from "@dcloudio/uni-app";
// import NeedVip from '@/components/NeedVip.vue';
import config from "@/config/config";
import projectConfig from "@/config/project/index.js";

const storageName = "messageList";
const userStore = useUserStore();
let pagePaddingBottom = ref(256);
provide("askAi", askAi);
// provide('refreshAi', refreshAi);
onLoad((e) => {
  console.log("chat-onload");
  useChat.resetConversation();
  useChat.setChatListByStorage();
});
let userAsk = ref("");
let userQuestion = ref("");
const useChat = useChatStore();
const chatStore = useChatStore();
const questionInput = ref(null);
const userInfo = computed(() => {
  return userStore.userInfo;
});
let aiSearchObj = {};
let userInput = ref("");
let maxHeight = ref('80rpx');

const expireVipModal = ref(false);
let modalType = ref('');
let localChatModal = uni.getStorageSync('chatmodal');
modalType.value = localChatModal ? localChatModal : 'v3';

// 是否拦截 false不拦截，true拦截
const showPage = ref(true)
const isNavBarClick = ref(false)


// function onClickLeft() {
//   isNavBarClick.value = true
//   uni.navigateBack()

//   setTimeout(() => {
//     isNavBarClick.value = false
//   }, 100);
// }



// function beforeleave() {
//   if (isNavBarClick.value) {
//     uni.navigateBack()
//   }
//   showPage.value = false

//   setTimeout(() => {
//     showPage.value = true
//   }, 0);
// }

let chatModal = computed(() => {
  const name = "deepseek-" + modalType.value;
  console.log('chatModal-conmputed', name);
  uni.setStorageSync("chatModal", name);
  return name;
});
onMounted(() => {
  debugger;
  uni.removeStorageSync('chatModal')

});
onShow(() => {
  // useChat.setChatListByStorage();
  aiSearchObj = getApp().globalData._query;
  console.log("进入ai会话页-onshow-拿到的参数", aiSearchObj);
  if (Object.keys(aiSearchObj).length) {
    decideAiApi();
  }
  // 隐藏tabbar
  uni.hideTabBar();
  setTimeout(() => {
    uni.pageScrollTo({
      scrollTop: 999999,
      duration: 0,
    });
  }, 500);
});
onHide(() => {
  chatStore.setChatStorage();
  getApp().globalData._query = {};
});
function userChangeInput(e) {
  let a = questionInput;
  callback({
    value: value + 1,
    cursor: 0,
  });
  // console.log('user input', e);
}
function switchModal() {
  console.log('function-switchModal-before', modalType.value)
  modalType.value = modalType.value.includes('v') ? "r1" : 'v3';
  console.log('function-switchModal-after', modalType.value)

}
function goHome() {
  uni.switchTab({
    url: config.page.index,
  });
}
/**
 * @description 根据决定AI的api
 */
async function decideAiApi() {
  const { id, type, text, prompt, question } = aiSearchObj;
  if (prompt) {
    // 直接按照提示词查询
    chatStore.addChat({
      apiType: "stream",
      answerType: "ai",
      question: prompt,
      fresh: "req",
      freshIsAi: true,
    });

  } else if (id) {
    // 查询问题属性
    let aiData = {},
      apiType = "",
      answerType = "";
    let req = {
      attrStr: id,
    };
    if (type && type.title) {
      req.typeName = type.title;
    }
    if (type.id == 33) {
      // 涨粉文案
      apiType = "normal";
      answerType = "questionBank";
    } else if (type.id == 32 || type.id == 35) {
      // 百问百答接口
      apiType = "stream";
      answerType = "questionBank";
      req.question = question;
    } else {
      apiType = "stream";
      answerType = "questionBank";
      aiData.fresh = "answer";
    }
    if (question) {
      aiData.question = question;
    }
    aiData.apiType = apiType;
    aiData.answerType = answerType;
    aiData.reqData = req;
    chatStore.addChat(aiData);

  } else if (type.type == "function") {
    // 普通功能
    chatStore.addChat({
      apiType: "stream",
      answerType: "ai",
      apiUrl: "chat_message/sendAiCreate",
      question: text,
      freshIsAi: false,
      reqData: {
        promptContent: text,
        promptTitle: type.title,
        promptType: "生活",
      },
    });

  }
}
async function inputAskAi() {
  await userStore.getUserInfo();
  uni.setStorageSync('isFirstVisit', true)

  if (uni.getStorageSync("userInfo").level === 0) {
    for (let key in projectConfig.chat.chatVipShow) {
      if (uni.getStorageSync("userInfo")["key"] == 0) {
        return (expireVipModal.value = true);
      }
    }
  }

  // if (uni.getStorageSync("userInfo").level === 0) {
  //   console.log(
  //     uni.getStorageSync("userInfo").freeCount === 0,
  //     uni.getStorageSync("userInfo").level === 0
  //   );

  //   return (expireVipModal.value = true);
  // }
  debugger;
  if (!userInput.value.trim()) {
    Toast.fail("请输入问题");
    return;
  }
  if (loginRedirect()) {
    // let questionContent = questionInput.value.value;
    // questionInput.value.value = '';
    askAi({ chatModal: chatModal.value, prompt: userInput.value });

    userInput.value = "";
  }
}
/**
 *
 * @param {*} param0
 * @param {String} param0.prompt 问ai的提示词
 * @param {String} param0
 */
async function askAi(obj) {
  console.log("问ai");
  userInput.value = "";
  let prompt = typeof obj == "object" ? obj.prompt : obj;
  chatStore.addChat({
    apiType: "stream",
    answerType: "ai",
    question: prompt,
  });

}

function addQuestion(content) {
  chatStore.addChat({
    content: content,
  });
}
function handleContent() { }

function clearChat() {
  console.log("用户点击清除");

  chatStore.clearChat();
}
function lineChange(evt) {
  let lineCount = evt.detail.lineCount > 1 ? evt.detail.lineCount : 1;
  pagePaddingBottom.value = 248 + (lineCount * 45);
  console.log('function-lineChange', pagePaddingBottom.value);
}

const handleInput = (evt) => {
  const value = evt.detail.value;
  // userInput.value = value;
  // console.log('evt-handleInput', userInput.value, userInput.value.length);
  // 在 nextTick 确保内容更新后再滚动
  if (value && value.length) {
    maxHeight.value = '320rpx';
  }
}
</script>
<script>
// 只能在App.vue里监听应用的生命周期
// export default {
//   onLoad: function (options) {
//
//     console.log('App Launch')
//     console.log('应用启动路径：', options.path)
//   },
//   onShow: function (options) {
//     console.log('App Show')
//     console.log('应用启动路径：', options.path)
//   },
//   onHide: function () {
//     console.log('App Hide')
//   }
// }
</script>
<style lang="less">
page {}

#fixed-input-wrap {
  padding-top: 30rpx;
  padding-bottom: 40rpx; // 76rpx;
  justify-content: space-around;
  // padding-top: 0.4rem;
  // padding-bottom: 1.3rem;
  background-color: var(--a-adapter-bg-color);

  textarea {
    color: var(--a-one-text-color);
  }
}

#nav-top {
  // position: fixed;
  // background-color: #fff;
}

.send {
  width: 104rpx;
  height: 66rpx;
  line-height: 66rpx;
  border-radius: 80rpx / 70rpx; // horizontal/vertical radius for elliptical shape


  box-sizing: border-box;
}

#input-wrap {
  display: flex;
  width: 100%;
  // height: 82rpx;
  // margin: 0 32rpx;
  padding-left: 24rpx;
  padding-right: 8rpx;
  padding-top: 8rpx;
  padding-bottom: 8rpx;
  justify-content: space-between;
  align-items: center;
  border-radius: 41rpx 41rpx 41rpx 41rpx;
  border: 2rpx solid var(--a-main-color);

  input {
    margin: 21rpx 0;
    flex: 1;
  }
}

hr {
  padding: 1rem 0;
}

#question-btn {
  text-align: center;
  border-radius: 50%;
  display: block;

  #question-icon {
    background-color: #fff;
  }

  i {
    background: #fff;
    border-radius: 50%;
    color: var(--a-main-color);
  }
}

#clear-chat {
  // position: fixed;
  // right: 25rpx;
  // top: 180rpx;
  // width: 147rpx;
  margin-right: 18rpx;
  border-radius: 35rpx 35rpx 35rpx 35rpx;

  .ai-icon-clean {
    margin-right: 12rpx;
  }
}



button[type=primary] {
  background-color: var(--a-main-color);
}

.thinkking rich-text {
  color: rgba(255, 255, 255, .85)
}

.fixed-footer {
  padding-left: 24rpx;
  padding-right: 24rpx;
  padding-bottom: 54rpx;
  box-sizing: border-box;
  border: none;
  background-color: rgba(33, 33, 66, 1);
}

.bottom-list {


  button {
    height: 64rpx;
    display: inline-block;
    box-sizing: border-box;
    line-height: 64rpx;
    padding-left: 19rpx;
    padding-right: 19rpx;
    font-size: 24rpx;
    background: #3D3D63;
    border-radius: 35rpx 35rpx 35rpx 35rpx;
    // border: 2px solid #3D3D63;
    color: #fff;

    .iconfont {
      vertical-align: middle;
    }

    &:after {
      border: none !important;
    }

    &.active {
      background: rgba(131, 205, 136, 0.1);
      color: var(--a-main-color);
    }
  }
}
</style>
<style lang="scss" scoped>
textarea {
  width: 100%;
  // padding: 10rpx;
  // margin: 10rpx 0;
  line-height: 45rpx;
  box-sizing: border-box;

  // &::-webkit-scrollbar {
  //   display: none; // Hide scrollbar
  // }
}
</style>
